package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.bean.Book;
import org.example.exception.*;
import org.example.mapper.BookMapper;
import org.example.service.BookService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Override
    public JsonResult findBook(){
        return ResultTool.success(list());
    }

    @Override
    public JsonResult findBook(int page) {
        //之前确认分页信息 page：页码：10：每页显示多少条
        Page<Book> p = Page.of(page, 10);
        List<Book> list = list(p);
        p.setRecords(list);
        return ResultTool.success(p);
    }
    @Override
    public JsonResult findBookById(String id){
        Book one = getById(id);
        return ResultTool.success(one);
    }
    @Override
    public JsonResult findBookByname(String name,int page){
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        Page<Book> of = Page.of(page, 10);
        List<Book> list = list(of, wrapper);
        of.setRecords(list);
        return ResultTool.success(of);
    }
    @Override
    public JsonResult saveBook(Book book){
        boolean save=save(book);
        if (!save){
            throw new UserSaveException("添加图书失败");
        }
        return ResultTool.success("success");
    }
    @Override
    public JsonResult updateBook(Book book){
        boolean update=updateById(book);
        if (!update){
            throw new UserSaveException("更新图书失败");
        }
        return ResultTool.success("success");
    }
    @Override
    public JsonResult removeBook(String id){
        boolean remove=removeById(id);
        if (!remove){
            throw new UserSaveException("删除用户失败");
        }
        return ResultTool.success("success");
    }
    @Override
    public JsonResult updateBookStatus(String id,int status){
        UpdateWrapper<Book> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.set("status",status);
        boolean update=update(wrapper);
        if (!update){
            throw new UserRemoveException("修改状态失败");
        }
        return ResultTool.success("success");
    }

}
